import React, { Component } from "react";
import { connect } from "dva";
import moment from "moment";
import { Input, Button, DatePicker, Table, Modal, message } from "antd";
import * as ajax from "../../../services/api";

const { confirm } = Modal;
const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD";

@connect(state => ({
  global: state.global,
  currentUser: state.user.currentUser
}))
export default class SendRecord extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      selectedRowIds: [], //需要删除的信息id值集合
      listPage: [], //表格数据
      selectedRowKeys: [],
      uid: this.props.currentUser.perId,
      input_val: "", //关键字输入框
      startDate: "",
      endDate: ""
    };
  }

  componentDidMount() {
    this.search();
  }

  //输入框的书写
  inputTracknameChange = e => {
    // let tmp = Object.assign({}, this.state.ajaxPagePara);
    // tmp.data.Trackname = e.target.value.trim();
    console.log(e.target.value.trim());
    this.setState({
      input_val: e.target.value.trim()
    });
  };

  //时间选择
  onChangeTime = (date, dateString) => {
    this.setState({
      startDate: dateString[0],
      endDate: dateString[1]
    });
  };

  //点击搜索
  search = () => {
    ajax
      .messageRecordList({
        pageNumber: 1,
        pageSize: 50,
        uid: this.state.uid,
        startDate: this.state.startDate,
        endDate: this.state.endDate,
        serachContent: this.state.input_val
      })
      .then(
        data => {
          console.log("wewewe", data);
          this.setState({
            listPage: data.data.data
          });
        },
        err => {
          console.log("err", err);
        }
      );
  };

  //重置
  resetQueryCond = () => {
    this.setState(
      {
        startDate: "",
        endDate: "",
        input_val: ""
      },
      () => {
        this.search();
      }
    );
  };

  // 批量删除
  handleDeleteList = () => {
    let _this = this;
    const key_number = this.state.selectedRowIds.length;
    const key_id = this.state.selectedRowIds;
    console.log("id集合" + key_id);
    if (key_number <= 0) {
      message.warning("请选择需要删除的信息！");
    } else {
      console.log(this.state.selectedRowIds);
      confirm({
        title: "是否删除所选方案，删除后方案不可找回。是否确认删除？",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          _this.orderDelete(key_id);
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    }
  };

  // 订单删除
  orderDelete = orderID => {
    console.log("orderID", orderID);
    ajax.messageDeleteSelectMessage({ ids: orderID.join(",") }).then(
      data => {
        console.log("消息删除", data);
        this.setState({
          selectedRowIds: [],
          selectedRowKeys: []
        });
        this.search();
      },
      err => {
        console.log("消息删除失败", err);
        message.warning("消息删除失败！" + err);
      }
    );
  };

  showDeleteConfirm = orderID => {
    console.log(orderID);
    let _this = this;
    confirm({
      title: "是否删除所选信息，删除后无法找回。是否确认删除？",
      okText: "确认",
      cancelText: "取消",
      onOk() {
        _this.orderDeleteXiao(orderID);
      },
      onCancel() {
        console.log("Cancel");
      }
    });
  };

  orderDeleteXiao = orderID => {
    console.log("orderID", orderID);
    ajax.messageDeleteMessageById({ perNewsRelaId: orderID }).then(
      data => {
        console.log("消息删除", data);
        this.search();
      },
      err => {
        console.log("消息删除失败", err);
        message.warning("消息删除失败！" + err);
      }
    );
  };

  // 表格渲染
  renderOrderList = () => {
    const pageInitStudent = {
      defaultPageSize: 10,
      showQuickJumper: true,
      pageSizeOptions: ["5", "10", "15", "20", "25"],
      showSizeChanger: true
    };

    const selectedRowKey = this.state.selectedRowKeys;
    const rowSelection = {
      selectedRowKeys: selectedRowKey,

      onChange: selectedRowKeys => {
        console.log("selectedRowKeys", selectedRowKeys);

        this.setState(
          {
            selectedRowKeys
          },
          () => {
            console.log("selectedRowKeys-more", this.state.selectedRowKeys);
          }
        );
      },
      onSelect: (record, selected, selectedRows) => {
        const selectId = this.state.selectedRowIds;
        if (selected === true) {
          selectId.push(record.perNewsRelaId);
        } else {
          for (let i = 0; i < selectId.length; i++) {
            if (selectId[i] === record.perNewsRelaId) {
              selectId.splice(i, 1);
              break;
            }
          }
        }
        this.setState({
          selectedRowIds: selectId
        });
        console.log(
          `record:`,
          record.perNewsRelaId,
          `selected:`,
          selected,
          `selectedRows:`,
          selectedRows
        );
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        let selectId = [];
        if (selected === true) {
          for (let i = 0; i < selectedRows.length; i++) {
            selectId.push(selectedRows[i].perNewsRelaId);
          }
        } else {
          selectId = [];
          // selectedRowKeys:selectedRowKey
        }
        this.setState({
          selectedRowIds: selectId
        });
        console.log(
          `selected:`,
          selected,
          `selectedRows:`,
          selectedRows,
          `changeRows:`,
          changeRows
        );
      }
    };

    /*01开头：系统通知
02开头：任务通知
03开头：企业通知
04开头：考试通知
05开头：公安通知
06开头：平台通知 */
    const noticeAwars = {
      "01": "系统通知",
      "02": "任务通知",
      "03": "企业通知",
      "04": "考试通知",
      "05": "公安通知",
      "06": "平台通知"
    };

    const columns = [
      {
        title: "消息类型",
        dataIndex: "messageType",
        key: "messageType",
        render: text => (
          <span style={{ color: "#666" }}>
            {noticeAwars[text.substr(0, 2)]}
          </span>
        )
      },
      {
        title: "标题",
        dataIndex: "title",
        key: "title",
        render: (text, record) => (
          <span>
            {record.status == "1" ? (
              <span style={{ color: "#999" }}>{record.title}</span>
            ) : (
              <span style={{ color: "#666" }}>{record.title}</span>
            )}
          </span>
        )
      },
      {
        title: "时间",
        dataIndex: "sendTime",
        key: "sendTime"
      }
    ];

    const tmp = this.state.listPage.map((val, i) => {
      val.key = i + 1;
      return val;
    });

    return (
      <Table
        dataSource={tmp}
        columns={columns}
        rowSelection={rowSelection}
        pagination={pageInitStudent}
      />
    );
  };

  render() {
    return (
      <div className="message-receive">
        <div className="form">
          <label>
            关键字：
            <Input
              style={{ width: 214 }}
              placeholder="请输入收件人/标题"
              onChange={this.inputTracknameChange}
              value={this.state.input_val}
              maxLength="20"
            />
          </label>
          <label style={{ marginLeft: 16 }}>
            接收时间：
            <RangePicker
              showTime={{ format: "HH:mm" }}
              format={dateFormat}
              onChange={this.onChangeTime}
              value={[
                this.state.startDate === ""
                  ? null
                  : moment(this.state.startDate, dateFormat),
                this.state.endDate === ""
                  ? null
                  : moment(this.state.endDate, dateFormat)
              ]}
            />
          </label>
          <Button
            style={{ marginLeft: 16 }}
            type="primary"
            onClick={this.search}
          >
            搜索
          </Button>
          <Button style={{ marginLeft: 16 }} onClick={this.resetQueryCond}>
            重置
          </Button>
        </div>
        <div className="receive-list">
          <div className="receive-row">
            <Button type="danger" ghost onClick={this.handleDeleteList}>
              批量删除
            </Button>
          </div>
        </div>
        {this.renderOrderList()}
      </div>
    );
  }
}
